import Logger from './Logger';
import MySequenceable from './MySequenceable';
import {MSG_SEND_METHOD} from './const';

const TAG = "BG_TASK_serviceExtAbility"
const BUNDLE_NAME = "com.example.myapplication";
const SERVICE_EXT_ABILITY_NAME = "DataTransAbility"
const context = globalThis.mainAbilityContext;

export default class BgTaskModel {
    caller = undefined;
    startingValue: number = 1
    constructor() {
        Logger.info(TAG, `BgTaskModel constructor`)
    }

    async onButtonGetCaller() {
        try {
            this.caller = await context.startAbilityByCall({
                bundleName: BUNDLE_NAME,
                abilityName: SERVICE_EXT_ABILITY_NAME
            });

            if (this.caller === undefined) {
                Logger.info(TAG, 'get caller failed');
                return;
            }
            Logger.info(TAG, 'get caller success');
            this.regOnRelease(this.caller);
            return true;
        } catch (error) {
            Logger.error(TAG, `get caller with error:  ${JSON.stringify(error)}`);
        }
    }

    // 注册caller的release监听
    private regOnRelease(caller) {
        try {
            caller.onRelease(msg => {
                Logger.info(TAG, 'caller onRelease is called' + msg)
            })
            Logger.info(TAG, 'caller register onRelease succeed')
        } catch (error) {
            Logger.error(TAG, `caller register onRelease failed with error:  ${JSON.stringify(error)}`);
        }
    }

    // call 调用，使用callee被调用端的 ‘calleeSendMsg' 方法，发送序列化数据
    async onButtonCallWithResult(originMsg, backMsg) {
        if (this.caller === undefined) {
            Logger.error(TAG, `caller is ${this.caller}`)
            return
        }
        try {
            let msg = new MySequenceable(this.startingValue, originMsg)
            const data = await this.caller.callWithResult(MSG_SEND_METHOD, msg)
            Logger.log(TAG, 'caller callWithResult succeed')

            let result = new MySequenceable(1, '')
            data.readSequenceable(result)
            backMsg(result.str)
            Logger.log(TAG, `caller result is [${result.num}, ${result.str}]`)
        } catch (error) {
            Logger.error(TAG, `caller callWithResult failed with ${error}`)
        }
    }

    // 释放caller通信接口
    onButtonRelease() {
        if (this.caller === undefined) {
            Logger.error(TAG, `caller is ${this.caller}`)
            return
        }

        try {
            this.caller.release()
            this.caller = undefined
            Logger.log(TAG, 'caller release succeed')
        } catch (error) {
            Logger.error(TAG, `caller release failed with ${error}`)
        }
    }

}